//
//  XGChatMessageModel.m
//  HuanXin
//
//  Created by monkey on 2019/11/22.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Hyphenate/Hyphenate.h>
#import <JSQMessagesViewController/JSQMessages.h>

#import "XGChatMessageModel.h"

@implementation XGChatMessageModel

@synthesize time = _time;

#pragma mark - 构造方法

- (instancetype)initWithDate:(NSDate *)date emmessage:(EMMessage *)emmessage
{
    EMMessageBody *body = emmessage.body;
    if (body.type == EMMessageBodyTypeImage) { // 图片消息
        EMImageMessageBody *imageBody = (EMImageMessageBody *)emmessage.body;
        NSString *path = imageBody.thumbnailLocalPath.length > 0 ? imageBody.thumbnailLocalPath : imageBody.localPath;
        JSQPhotoMediaItem *photoItem = [[JSQPhotoMediaItem alloc] initWithImage:[UIImage imageWithContentsOfFile:path]];
        self = [super initWithSenderId:emmessage.from senderDisplayName:emmessage.from date:date media:photoItem];
        [self setValue:@"[图片]" forKey:@"text"];
    } else if (body.type == EMMessageBodyTypeText) { // 文本消息
        self = [super initWithSenderId:emmessage.from senderDisplayName:emmessage.from date:date text:[(EMTextMessageBody *)emmessage.body text]];
    } else if (body.type == EMMessageBodyTypeVoice) { // 语音消息
        EMVoiceMessageBody *voiceBody = (EMVoiceMessageBody *)emmessage.body;
        NSData *audioData = [NSData dataWithContentsOfFile:voiceBody.localPath];
        JSQAudioMediaItem *audioItem = [[JSQAudioMediaItem alloc] initWithData:audioData];
        self = [super initWithSenderId:emmessage.from senderDisplayName:emmessage.from date:date media:audioItem];
        [self setValue:@"[语音]" forKey:@"text"];
    }
    
    if (self) {
        _emmessage = emmessage;
    }
    
    return self;
}

+ (instancetype)messageModelWithDate:(NSDate *)date emmessage:(EMMessage *)emmessage
{
    return [[self alloc] initWithDate:date emmessage:emmessage];
}

- (NSString *)time
{
    if (!_time) {
        _time = [self.date weiChatDateDescription];
    }
    
    return _time;
}
@end
